<?php

namespace app\service;

use app\common\BaseService;
use app\model\StoreBack as StoreBackModel;
use app\model\StoreBackOrder as StoreBackOrderModel;
use think\facade\Db;

class StoreBackService extends BaseService
{
  public static function getInstance(): StoreBackService
  {
    return parent::getInstance();
  }

  public static function getModel(): StoreBackOrderModel
  {
    return StoreBackOrderModel::getInstance();
  }

  public static function getDetailModel(): StoreBackModel
  {
    return StoreBackModel::getInstance();
  }

  public static function getDataByCondition($conditions, $order = ['id' => 'desc']) {
    return self::getModel()->getDataByCondition($conditions, $order);
  }

  /*
   * 批量退货处理
   */
  public static function createMultiBack($data)
  {
    $msg = [];
    // 获取退货申请号
    $cond = [
      ['insert_time', date('Y-m-d'), '>=']
    ];
    $outer = self::getModel()->getDataByCondition($cond);
    $arr = array_unique(array_column($outer, 'apply_number'));
    $num = str_pad(count($arr) + 1, 3, '0', STR_PAD_LEFT);
    $applyNumber = 'TH'.date('Ymd') . $num;
    // 新增退货信息
    $insertBack = [];
    $insertBackOrder = [
      'apply_number' => $applyNumber,
      'back_time' => $data['back_time'],
      'status' => 1,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    // 获取门店列表
    $baseList = UserService::getInstance()->storeAll();
    $baseList = array_column($baseList, 'basename', 'base');
    // 更新总部仓库
    $updateHouse = [];
    // 获取总部仓库数据
    $houseList = HouseService::getInstance()->getHouseJoinGoods([]);
    $houseList = array_column($houseList, null, 'goods_id');
    // 更新门店仓库
    $updateStore = [];
    // 获取门店仓库数据
    $conStore[] = ['status', 1, '='];
    $storeList = [];
    $storeRes = StoreService::getInstance()->getDataByCondition($conStore);

    foreach ($storeRes as $sv) {
      $str = '';
      // 内部数据
      if ($sv['goods_id']) {
        $str = $sv['goods_id'].'-'.$sv['base'];
        $storeList[$str] = $sv;
      }
    }
    foreach ($data['detail'] as $value) {
      $str = $value['goods_id'].'-'.$value['base'];
      if (!isset($houseList[$value['goods_id']])) {
        $msg[] = '商品有误';
        continue;
      }
      if (!isset($storeList[$str])) {
        $msg[] = '门店：'.$baseList[$value['base']].'，不存在商品“'.$houseList[$value['goods_id']]['name'].'”';
        continue;
      }
      // 门店库存
      $store = $storeList[$str];
      $house = $houseList[$value['goods_id']];
      if ($store['count'] < $value['count']) {
        $msg[] = '门店：'.$baseList[$value['base']].'，中商品“'.$houseList[$value['goods_id']]['name'].'”库存不足';
        continue;
      }
      // 新增back详情
      $insertBack[] = [
        'back_order_id' => 0,
        'goods_id' => $value['goods_id'],
        'count' => $value['count'],
        'base' => $value['base'],
        'price' => $house['price'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
      // 修改门店
      $updateStore[] = [
        'id' => $store['id'],
        'count' => strval($store['count']) - strval($value['count']),
        'total_amount' => round((strval($store['count']) - strval($value['count'])) * $store['price'], 2),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
      // 修改总部
      if (isset($updateHouse[$house['id']])) {
        $updateHouse[$house['id']]['count'] += $value['count'];
        $updateHouse[$house['id']]['total_amount'] = round($updateHouse[$house['id']]['count'] * $house['price'], 2);
      } else {
        $updateHouse[$house['id']] = [
          'id' => $house['id'],
          'count' => $house['count'] + $value['count'],
          'total_amount' => round(($house['count'] + $value['count']) * $house['price'], 2),
          'last_update_time' => date('Y-m-d H:i:s')
        ];
      }
    }
    if ($msg) {
      $msg = join('<br>', $msg);
      return ['status' => false, 'msg' => $msg];
    }
    self::getModel()->startTrans();
    try {
      // 新增store_back_order
      if ($insertBackOrder) {
        $res = self::getModel()
          ->insertGetId($insertBackOrder);
        if ($res === false) {
          throw new \Exception('新增store_back_order失败');
        }
      }
      // 新增store_back
      if ($insertBack) {
        foreach ($insertBack as &$v) {
          $v['back_order_id'] = $res;
        }
        $res1 = self::getDetailModel()->insertAll($insertBack);
        if (!$res1) {
          throw new \Exception('新增store_back失败');
        }
      }
      // 修改store_house
      if ($updateStore) {
        $res2 = StoreService::getModel()
          ->saveAll($updateStore);
        if ($res2 === false) {
          throw new \Exception('修改store_house失败');
        }
      }
      // 修改store_house
      if ($updateHouse) {
        $res3 = HouseService::getModel()
          ->saveAll($updateHouse);
        if ($res3 === false) {
          throw new \Exception('修改house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

  public function getBackJoinStore($conditions, $order = ['so.id' => 'DESC']) {
    $conditions[] = ['sb.status', 1, '='];
    $query = Db::name('store_back')
      ->alias('sb')
      ->field('sb.*, so.apply_number, so.back_time, g.name, u.basename, g.category_id, g.process, g.unit, c.category_name')
      ->join('goods g', 'g.id = sb.goods_id', 'LEFT')
      ->join('store_back_order so', 'so.id = sb.back_order_id', 'LEFT')
      ->join('category c', 'c.id = g.category_id', 'LEFT')
      ->join('user u', 'u.base = sb.base', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }


}